<?php

namespace control;
/*
*社保核算类
*/

class insureClass extends adIndexClass
{
    private const title = '社保核算';
    private const page  = 'insure';
    private const table = 'insure';
    public string $checkIdCard = "/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/";

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'name'      => [
                        'name'  => L('salary.table.yuan_gong'),
                        'width' => 200,
                    ],
                    'subject' => [
                        'name'  => L('salary.table.fei_kuan_ke_mu'),
                        'width' => 200,
                    ],
                    'payMoon'  => [
                        'name'  => L('salary.table.jkyf'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'moon'         => [
                        'name'  => L('salary.table.zsyf'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'base'          => [
                        'name'  => "缴费基数(" . static::$unit . ")",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'personal'    => [
                        'name'  => "个人缴纳(" . static::$unit . ")",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'company'    => [
                        'name'  => "单位缴纳(" . static::$unit . ")",
                        'width' => 200,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = "您还没有导出的权限";
        }  else {
            $tr    = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by payMoon desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $k=>$array){
                $column = [];
                $staff = query("staff", " stid = '$array[stid]' ");
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '序号'=>$k+1,
                            '员工'=>$staff['name'],
                            '费款科目'=>$array['subject'],
                            '缴款月份'=>$array['payMoon'],
                            '所属月份'=>$array['moon'],
                            '缴费基数'=>$array['base'],
                            '个人缴纳'=>$array['personal'],
                            '单位缴纳'=>$array['company'],
                            default=>'',
                        };
                    }
                }
                $tr[] = $column;
            }
            $text = $this->control['name'] . "导出了社保扣款";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $tr, "社保扣款.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('salary.table.xing_ming') => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                    L('salary.table.fei_kuan_ke_mu')     => select(array("name" => "subject", 'option' => ['基本医疗','大额医疗','养老保险','失业保险','工伤保险'])),
                    L('salary.table.jkyf') => text(array("name" => "payMoon", 'laydate' => ['type' => 'month', 'range' => '~'])),
                ],
                [
                    L('salary.table.zsyf')   => text(array("name" => "moon", 'laydate' => ['type' => 'month', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 查询条件
     *
     * @return string
     */
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power("insure", "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('salary.table.shan_chu') . "</span>\n";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*社保数据-列表页-查询结果*/
    public function homeSearch()
    {
        //全等查询数组
        $equal = array(
            "stid"    => $this->post('stid'),//员工
            "subject" => $this->post('subject'),//费款科目
        );
        $and   = '';
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and stid in (select stid from staff where jobId in (select id from job where departmentId = '{$this->post('departmentId')}')) ";
        }
        if ($this->post('payMoon')) {
            $timeArr = explode(' ~ ', $this->post('payMoon'));
            $and     .= " and payMoon >='{$timeArr[0]}' and payMoon <='{$timeArr[1]}'";
        }
        if ($this->post('moon')) {
            $timeArr = explode(' ~ ', $this->post('moon'));
            $and     .= " and moon >='{$timeArr[0]}' and moon <='{$timeArr[1]}'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'payMoon',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("=" => $equal)) . $and;
        $page  = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "name":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        }  else {
            $exampleData[] = [
                1, '张三', '居民身份证', '041323199504290001', '南岸区社会保险公共业务办（医保）', '103415xx', '20776168xx', '基本医疗保险费', '职工基本医疗保险(个人缴纳)', '', '2023-11-01', '2023-11-30', 3000, 4118, 0.02, 82.36
            ];
            $exampleData[] = [
                2, '张三', '居民身份证', '041323199504290001', '南岸区社会保险公共业务办（医保）', '103415xx', '20776168xx', '基本医疗保险费', '职工基本医疗保险(单位缴纳)', '', '2023-11-01', '2023-11-30', 3000, 4118, 0.085, 350.03
            ];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '序号'=>$example[0],
                            '姓名'=>$example[1],
                            '身份证件类型'=>$example[2],
                            '身份证件号码'=>$example[3],
                            '社保经办机构'=>$example[4],
                            '单位编号'=>$example[5],
                            '人员编号'=>$example[6],
                            '参保费种'=>$example[7],
                            '征收品目'=>$example[8],
                            '征收子目'=>$example[9],
                            '费款所属日期起'=>$example[10],
                            '费款所属日期止'=>$example[11],
                            '职工工资'=>$example[12],
                            '缴费基数'=>$example[13],
                            '费率'=>$example[14],
                            '本期应缴费额'=>$example[15],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
            $text   = $this->control['name'] . "下载了" . self::title . "导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入分析*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = '您还没有导入的权限';
        } else {
            $subjectArray = array(
                "失业保险(个人缴纳)"       => array("name" => "失业保险", "pay" => "个人缴纳"),
                "失业保险(单位缴纳)"       => array("name" => "失业保险", "pay" => "单位缴纳"),
                "工伤保险"             => array("name" => "工伤保险", "pay" => "单位缴纳"),
                "职工基本养老保险(个人缴纳)"   => array("name" => "养老保险", "pay" => "个人缴纳"),
                "职工基本养老保险(单位缴纳)"   => array("name" => "养老保险", "pay" => "单位缴纳"),
                "职工基本医疗保险(个人缴纳)"   => array("name" => "基本医疗", "pay" => "个人缴纳"),
                "职工基本医疗保险(单位缴纳)"   => array("name" => "基本医疗", "pay" => "单位缴纳"),
                "职工大额医疗互助保险(个人缴纳)" => array("name" => "大额医疗", "pay" => "个人缴纳"),
                "职工大额医疗互助保险(单位缴纳)" => array("name" => "大额医疗", "pay" => "单位缴纳"),
            );
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x            = 0;
            $log          = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $IDCard  = $cell['身份证件号码'];//身份证号码
                    $talent  = query('talent_pool', " idCard = '$IDCard'");
                    $staff   = query("staff", "talentId = '$talent[id]'");
                    $payMoon = date("Y-m", strtotime($cell['费款所属日期起']));//缴款月份
                    $moon    = date("Y-m");//所属月份-默认当前月份
                    $subject = $subjectArray[$cell['征收品目']];//费款科目数组
                    $field   = [
                        "stid"    => $staff['stid'],//员工ID
                        "subject" => $subject['name'],//费款科目
                        "payMoon" => $payMoon,//缴款月份
                        "moon"    => $moon,//所属月份
                        "base"    => $cell['缴费基数'],//缴费基数
                    ];
                    //缴费对象
                    if ($subject['pay'] == "个人缴纳") {
                        $field['personal'] = $cell['本期应缴费额'];
                    } elseif ($subject['pay'] == "单位缴纳") {
                        $field['company'] = $cell['本期应缴费额'];
                    }
                    $annotation = [
                        'stid'    => L('salary.table.yuan_gong'),
                        'subject' => L('salary.table.fei_kuan_ke_mu'),
                        'payMoon' => '费款所属日期起',
                        'moon'    => L('salary.table.zsyf'),
                    ];
                    $rules      = [
                        'stid'    => 'required',
                        'subject' => 'required',
                        'payMoon' => 'required',
                        'moon'    => 'required',
                    ];
                    // 校验是否符合规则
                    $vt     = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    $line   = str_replace(['{{i}}'], [$row_list], L('job.other.line'));
                    $insure = query("insure", "stid = '$staff[stid]' and subject = '$subject[name]' and payMoon = '$payMoon' and moon = '$moon'");
                    if ($result === false) {
                        $log .= "\n" . $line . "：" . $vt->getErrs()[0];  // 多个规则提示最前面一条
                    } elseif (preg_match($this->checkIdCard, $IDCard) == 0) {
                        $log .= "\n" . $line . "：" . str_replace(['{{idCard}}'], [$IDCard], L('salary.table.idCardError'));
                    } elseif (self::total(['table'=>'work_sign_record','where'=>"month = '$field[payMoon]' and stid = '$field[stid]' and isPay = 1"]) >0){
                        $log .=  "\n".$line."：此缴款月份的员工工资条已拨付";
                    }else {
                        if (!empty($insure['id'])) {
                            $warn = update(array(
                                "table" => "insure",
                                "field" => $field,
                                'where' => "id = '$insure[id]'"
                            ));
                        } else {
                            $field = array_merge($field, array(
                                "id" => suiji(),
                            ));
                            $warn  = insert(array(
                                "table" => "insure",
                                "field" => $field
                            ));
                        }

                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $log .= "\n" . $line . "：" . L('job.other.import_success');
                        } else {
                            $log .= "\n" . $line . "：" . L('job.other.import_failed');
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$log,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = str_replace(['{{staffName}}', '{{fileName}}'], [$this->control['name'], $_FILES['file']['name']], L('job.other.import_log')) . '：' . $log;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        switch ($act) {
            default:
                $act      = 'del';
                $msg      = L('salary.table.delInsure');
                $title    = self::page . 'Delete';
                $function = 'delete';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('salary.table.nmzscdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('salary.table.nygsjdmzxzn');
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if (self::total(['table'=>'work_sign_record','where'=>"month = '$info[payMoon]' and stid = '$info[stid]' and isPay = 1"]) >0){
                    $warn = "删除失败：此缴款月份的员工工资条已拨付";
                }else{
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = L('salary.table.sccg');
                    $x++;
                }
                $text .= str_replace(['{{name}}', '{{month}}', '{{id}}'], [self::findStaff($info['stid']), $info['moon'], $id], L('salary.table.insure_del_text')) . $warn . "。\n";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('salary.table.insure_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('salary.table.insure_del_warn'));
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'姓名',
                    'aliasName'=>'姓名',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'身份证件类型',
                    'aliasName'=>'身份证件类型',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'身份证件号码',
                    'aliasName'=>'身份证件号码',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'社保经办机构',
                    'aliasName'=>'社保经办机构',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'单位编号',
                    'aliasName'=>'单位编号',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'人员编号',
                    'aliasName'=>'人员编号',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'参保费种',
                    'aliasName'=>'参保费种',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'征收品目',
                    'aliasName'=>'征收品目',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'征收子目',
                    'aliasName'=>'征收子目',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'费款所属日期起',
                    'aliasName'=>'费款所属日期起',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'费款所属日期止',
                    'aliasName'=>'费款所属日期止',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'职工工资',
                    'aliasName'=>'职工工资',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'缴费基数',
                    'aliasName'=>'缴费基数',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'费率',
                    'aliasName'=>'费率',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'本期应缴费额',
                    'aliasName'=>'本期应缴费额',
                    'isMust'=>false,
                ],
            ]
        };
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'序号',
                    'aliasName'=>'序号',
                ],
                [
                    'columnName'=>'员工',
                    'aliasName'=>'员工',
                ],
                [
                    'columnName'=>'费款科目',
                    'aliasName'=>'费款科目',
                ],
                [
                    'columnName'=>'缴款月份',
                    'aliasName'=>'缴款月份',
                ],
                [
                    'columnName'=>'所属月份',
                    'aliasName'=>'所属月份',
                ],
                [
                    'columnName'=>'缴费基数',
                    'aliasName'=>'缴费基数',
                ],
                [
                    'columnName'=>'个人缴纳',
                    'aliasName'=>'个人缴纳',
                ],
                [
                    'columnName'=>'单位缴纳',
                    'aliasName'=>'单位缴纳',
                ],

            ]
        };
    }
}
